package io.sundial.job.bind.impl;

import io.sundial.job.JobContext;
import io.sundial.job.JobParameter;
import io.sundial.job.bind.JobData;
import io.sundial.job.bind.JobField;
import io.sundial.job.bind.JobResolver;
import io.sundial.util.StrKit;

/**
 * 基本类型 转换器
 *
 * @author Payne 646742615@qq.com
 * 2019/1/7 21:27
 */
public class PrimitiveResolver implements JobResolver {

    @Override
    public boolean supports(JobField field) {
        return field.type == boolean.class
                || field.type == byte.class
                || field.type == short.class
                || field.type == char.class
                || field.type == int.class
                || field.type == float.class
                || field.type == long.class
                || field.type == double.class;
    }

    @Override
    public JobParameter resolve(JobField field) {
        return field.type == boolean.class
                ? new JobParameter(field.name).setEditor("checkbox").setValue(field.value.toString())
                : new JobParameter(field.name).setEditor("text").setValue(field.value.toString());
    }

    @Override
    public Object resolve(JobField field, JobData data, JobContext context) {
        String value = data.get(field.name);
        return StrKit.isEmpty(value) ? DEFAULT
                : field.type == boolean.class ? Boolean.valueOf(value)
                : field.type == byte.class ? Byte.valueOf(value)
                : field.type == short.class ? Short.valueOf(value)
                : field.type == char.class ? value.charAt(0)
                : field.type == int.class ? Integer.valueOf(value)
                : field.type == float.class ? Float.valueOf(value)
                : field.type == long.class ? Long.valueOf(value)
                : field.type == double.class ? Double.valueOf(value)
                : DEFAULT;
    }
}
